package com.zhida.smartcontrol.pagectrl.projectdetail.warning;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.jay.tools.recycler.OnItemClick;
import com.jay.tools.recycler.decoration.RecyclerViewItemDecoration;
import com.jay.tools.utils.DimenUtils;
import com.yanzhenjie.kalle.Kalle;
import com.zhida.smartcontrol.R;
import com.zhida.smartcontrol.mvp.MVPBaseFragment;
import com.zhida.smartcontrol.pagectrl.projectdetail.zonemanager.ZoneManagerFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

/**
 * author: tanjianpei
 * date: 2019/10/11 011 9:14
 * description: 故障报警
 */
public class WarningFragment extends MVPBaseFragment<WarningContract.View, WarningPresenter> implements WarningContract.View {
    @BindViews({R.id.tv_all, R.id.tv_dl, R.id.tv_dy, R.id.tv_pdg})
    List<TextView> mTvs;
    @BindView(R.id.recycler_view)
    RecyclerView mRView;
    @BindView(R.id.refresh)
    SwipeRefreshLayout mRefresh;

    private WarningAdapter mAdapter;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mHandler.postDelayed(requestWarning, 5000);
                    break;
                case 1:
                    mHandler.removeCallbacks(requestWarning);
                    break;
                case 2:
                    mHandler.post(requestWarning);
                    break;
            }
        }
    };
    private Runnable requestWarning = new Runnable() {
        @Override
        public void run() {
            assert getArguments() != null;
            mPresenter.requestWarning(mSwitchType, getArguments().getString("id"), page, true);
        }
    };
    private String mSwitchType = "";
    private int page = 1;


    @Override
    protected Object getLayout() {
        return R.layout.fragment_warning;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        mHandler.obtainMessage(2).sendToTarget();
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        mHandler.obtainMessage(1).sendToTarget();
        Kalle.cancel("ZoneManagerPresenter");
    }

    public static WarningFragment newInstance(String projectId, String projectName) {
        Bundle args = new Bundle();
        args.putString("id", projectId);
        args.putString("pName", projectName);
        WarningFragment fragment = new WarningFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick({R.id.tv_all, R.id.tv_dl, R.id.tv_dy, R.id.tv_pdg})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_all:
                mSwitchType = "";
                mTvs.get(0).setTextColor(Color.parseColor("#3862FF"));
                mTvs.get(1).setTextColor(Color.parseColor("#666666"));
                mTvs.get(2).setTextColor(Color.parseColor("#666666"));
                mTvs.get(3).setTextColor(Color.parseColor("#666666"));
                break;
            case R.id.tv_dl:
                mSwitchType = "1";
                mTvs.get(0).setTextColor(Color.parseColor("#666666"));
                mTvs.get(1).setTextColor(Color.parseColor("#3862FF"));
                mTvs.get(2).setTextColor(Color.parseColor("#666666"));
                mTvs.get(3).setTextColor(Color.parseColor("#666666"));
                break;
            case R.id.tv_dy:
                mSwitchType = "2";
                mTvs.get(0).setTextColor(Color.parseColor("#666666"));
                mTvs.get(1).setTextColor(Color.parseColor("#666666"));
                mTvs.get(2).setTextColor(Color.parseColor("#3862FF"));
                mTvs.get(3).setTextColor(Color.parseColor("#666666"));
                break;
            case R.id.tv_pdg:
                mSwitchType = "3";
                mTvs.get(0).setTextColor(Color.parseColor("#666666"));
                mTvs.get(1).setTextColor(Color.parseColor("#666666"));
                mTvs.get(2).setTextColor(Color.parseColor("#666666"));
                mTvs.get(3).setTextColor(Color.parseColor("#3862FF"));
                break;
        }
        page = 1;
        mHandler.obtainMessage(0).sendToTarget();
        mRefresh.setRefreshing(true);
    }

    @Override
    protected void initLazy(Bundle savedInstanceState) {

        mRView.setLayoutManager(new LinearLayoutManager(getProxyActivity()));
        mRView.addItemDecoration(new RecyclerViewItemDecoration.Builder(getProxyActivity())
                .thickness(DimenUtils.dp2px(getProxyActivity(), 5))
                .color(Color.TRANSPARENT)
                .firstLineVisible(true)
                .lastLineVisible(true)
                .create());

        mAdapter = new WarningAdapter(null);
        mAdapter.bindToRecyclerView(mRView);
        mTvs.get(0).setTextColor(Color.parseColor("#3862FF"));
        View view = LayoutInflater.from(getProxyActivity()).inflate(R.layout.layout_empty_detail, null);
        mAdapter.setEmptyView(view);
        mAdapter.setOnLoadMoreListener(() -> {
            page++;
            mHandler.obtainMessage(0).sendToTarget();
        }, mRView);
        mRefresh.setOnRefreshListener(() -> {
            page = 1;
            mHandler.obtainMessage(0).sendToTarget();
            mRefresh.setRefreshing(true);
        });
        mAdapter.setClickListener(new OnItemClick<WarningBean.ListBean.RecordsBean>() {
            @Override
            public void onClick(WarningBean.ListBean.RecordsBean info, int tag) {
                switch (tag){
                    case 0:
                        NormalDialog dialog = new NormalDialog(getContext());
                        dialog.content("确定忽略这条信息吗?")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("温馨提示")
                                .btnNum(2)
                                .btnTextColor(
                                        R.color.c_666666, R.color.c_3862FF
                                )
                                .btnText("取消", "确定")
                                .titleTextSize(23f)
                                .show();
                        dialog.setOnBtnClickL((OnBtnClickL) () -> {
                                    dialog.dismiss();
                                },(OnBtnClickL) () -> {
                                    dialog.dismiss();
                                    mPresenter.processWarn(info.getAlarmType(),info.getId(),"IGNORED",true);
                                }
                        );
                        break;
                    case 1:
                        NormalDialog dialog1 = new NormalDialog(getContext());
                        dialog1.content("确定处理这条信息吗?")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("温馨提示")
                                .btnNum(2)
                                .btnTextColor(
                                        R.color.c_666666, R.color.c_3862FF
                                )
                                .btnText("取消", "确定")
                                .titleTextSize(23f)
                                .show();
                        dialog1.setOnBtnClickL((OnBtnClickL) () -> {
                                    dialog1.dismiss();
                                },(OnBtnClickL) () -> {
                                    dialog1.dismiss();
                                    mPresenter.processWarn(info.getAlarmType(),info.getId(),"PROCESSED",true);
                                }
                        );
                        break;
                }
            }
        });
    }

    @Override
    public void showData(WarningBean warningBean) {
        String[] title = new String[]{"全部异常", "电压异常", "电流异常", "其他异常"};

        for (int i = 0; i < title.length; i++) {
            TextView mTv = mTvs.get(i);
            mTv.setText(Html.fromHtml(title[i] + (i == 0 ? warningBean.getAllCount() : i == 1 ? warningBean.getVolCount() : i == 2 ? warningBean.getCulCount() : warningBean.getOtherCount())));
        }
        mAdapter.setProjectName(warningBean.getProjectName());
        if (page <= 1) {
            mAdapter.setNewData(warningBean.getList().getRecords());
            if (warningBean.getList().getRecords().size() < 10) {
                mAdapter.loadMoreEnd(true);
            }
        } else {
            mAdapter.addData(warningBean.getList().getRecords());
            if (warningBean.getList().getRecords().size() < 10) {
                mAdapter.loadMoreEnd(true);
            } else mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void processWarn() {
        page = 1;
        mHandler.obtainMessage(0).sendToTarget();
        mRefresh.setRefreshing(true);
    }
}
